package com.itheima.filter;

import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
//@WebFilter("/*")
public class LoginCheckFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //0.强转
        HttpServletRequest req= (HttpServletRequest) servletRequest;
        HttpServletResponse resp= (HttpServletResponse) servletResponse;

        //1.获取请求路径
        String uri=req.getRequestURI();
        log.info("请求路径:{}",uri);
        //2.判断是否是登录请求
        if(uri.contains("login")){
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //3.判断是否存在token不存在返回登录失败
        String token=req.getHeader("token");
        if(token==null){
            log.info("没有token");
            //设置响应
            resp.setStatus(401);
           // throw new BusinessException("未登录请先登录");
        }
        //4.校验token是否正确
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Integer id = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(id);
            log.info("解析token成功:{}",claims);
        } catch (Exception e) {
            resp.setStatus(401);
            //throw new BusinessException("未登录请先登录");
        }

        //5.放行
        filterChain.doFilter(servletRequest,servletResponse);

//        //清除当前线程的id
        CurrentHolder.remove();
    }

    @Override
    public void destroy() {

        Filter.super.destroy();
    }
}
